package com.atguigu.spzx.manager.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.atguigu.spzx.manager.service.ValidateCodeService;
import com.atguigu.spzx.model.vo.system.ValidateCodeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public ValidateCodeVo generateValidateCode() {
        //获取验证码、验证码图片数据、Key
        //使用hutool工具包中的验证码获取
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(130, 50, 4, 10);
        //拿到随机的验证码
        String code = circleCaptcha.getCode();
        //拿到验证码对应的图片数据
        String imageBase64 = circleCaptcha.getImageBase64Data();
        //生成唯一key
        String key= UUID.randomUUID().toString().replace("-","");
        //存入 key , 验证码到redis一份 ,后续需要对照验证码
        redisTemplate.opsForValue().set(key,code,3, TimeUnit.MINUTES);

        //封装验证码结果给前端  (key和验证码图片的数据)
        ValidateCodeVo validateCodeVo = new ValidateCodeVo();
        validateCodeVo.setCodeKey(key);
        validateCodeVo.setCodeValue(imageBase64);
        return validateCodeVo;
    }
}
